<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\Db;

class Category extends AdminController
{
    public function index()
    {
        $data=db('category')->select();
        return view('category/index',['data'=>$data]);
    }



    public function create()
    {

      $res = db('category')
            ->field('id,cname, path , concat(path, id, ",") as abc')
            ->order('abc')
            ->select();
        // $res=db('category')
        //     ->field('id, cname, path')
        //     ->order(' concat(path, id, ",") ')
        //     ->select();
        
        foreach($res as $k => $v){
            // 统计出现了多少个逗号
            $num =substr_count($v['path'], ',');
//            dump($num);
            // 重复指定空格出现多少次
            $res[$k]['nbsp'] =  str_repeat('---', ($num-1)*2);
        }
//        dump($res);die;
        return view('category/add',['res'=>$res]);
    }



    public function save(Request $request)
    {
        $data=$request->post();
//        $data=$request->post();
        if ($data['pid']!=0){
            $oldpath=db('category')->field('path')->where('id',$data['pid'])->find();
            $data['path']=$oldpath['path'].$data['pid'].',';

        }else{
            $data['path']='0,';
        }

        $num=substr_count($data['path'], ',');
        if ($num>2){

            return $this->error('最多添加二级分类');
        }else{
            $res=db('category')->insert($data);
            if ($res){
                return $this->success('添加成功','admin/category/index');
            }else{
                return $this->error('添加失败');
            }
        }

    }



    public function edit($id)
    {
        $data=db('category')->where('id',$id)->find();
//        dump($data);
//        die;

        return view('category/updata',['data'=>$data]);
    }


    public function update(Request $request,$id)
    {
        $p=$request->put();
//        dump($p);die;
        $data=[
            'cname'=>$p['cname']
        ];

        $res=db('category')->where('id',$id)->update($data);
        if ($res){
            return $this->success('更新成功','admin/category/index');
        }else{
            return $this->error('更新失败');
        }
    }



    public function del($id)
    {
        $data=db('category')->where('pid',$id)->field('id')->select();
//        dump($data);die;
        if (!$data){
            $res=db('category')->where('id',$id)->delete();
            if ($res){
                return $this->success('删除成功','admin/category/index');
            }else{
                return $this->error('删除失败');
            }
        }else{
            return $this->error('请先删除子分类');
        }

    }
}
